#!/bin/bash

#
# clusterInit.sh
# created by youngeryoyo
# of qloudgen to support cluster initalization 
# 

if [ $# != 4 ];then
  echo "Usage: clusterInit.sh configFile controllerIp gtmIp nodeIp"
  exit 1;
fi
configFile=$1
controllerIp=$2
gtmIp=$3
nodeIp=$4
configTemplate=pgxc_ctl.conf
database=dilithium

echo controllerIp:$controllerIp gtmIp:$gtmIp nodeIp:$nodeIp
# get local ip
#controllerIp=`LANG=C ifconfig $NIC | awk '/inet addr:/{ print $2 }' |  awk -F: '$2 !~ /127.0.0.1/{print $2 }'`

checkIp () {
  regex="\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\b"
  check=`echo $1 | egrep $regex | wc -l`
  if [ $check -eq 0 ];then
    echo "The string $1 is not a correct ip!"
    exit 2;
  fi
}

#check ip
checkIp $controllerIp
checkIp $gtmIp
checkIp $nodeIp

# generate config file template
if [ -f $configTemplate ]; then 
  cp $configTemplate $configFile
else
  echo "$configTemplate does not exist!"
  exit 3;
fi

# get controller local ip

# append some info 
cat >> $configFile <<EOF
gtmMasterServer=$gtmIp
gtmProxyServers=($nodeIp)
coordMasterServers=($nodeIp)
datanodeMasterServers=($nodeIp)
coordPgHbaEntries=($controllerIp/32 $gtmIp/32 $nodeIp/32)
datanodePgHbaEntries=($controllerIp/32 $gtmIp/32 $nodeIp/32)
EOF

# init db 
pgxc_ctl -c $PWD/$configFile init all

# create db
pgxc_ctl -c $PWD/$configFile Createdb $database

# add controllerIp gtmIp nodeIp on $database to pg_bha.conf on nodeIp
  source $configFile

  ssh $pgxcUser@$nodeIp "cat >> $coordMasterDir/pg_hba.conf" <<EOF
host $database all $controllerIp/32 md5
host $database all $gtmIp/32 md5
host $database all $nodeIp/32 md5
EOF

  ssh $pgxcUser@$nodeIp pg_ctl reload -Z coordinator -D $coordMasterDir

  ssh $pgxcUser@$nodeIp "cat >> $datanodeMasterDir/pg_hba.conf" <<EOF
host $database all $controllerIp/32 md5
host $database all $gtmIp/32 md5
host $database all $nodeIp/32 md5
EOF

  ssh $pgxcUser@$nodeIp pg_ctl reload -Z datanode -D $datanodeMasterDir

